package thread;

import jdk.nashorn.api.tree.ForOfLoopTree;

public class SyncDemo4 {//互斥的演示

    public static void main(String[] args) {
        //当双线程分别调用同一个对象的两个都上了锁的不同的方法,会发生互斥(互斥即同步)
        //如果其中一个没上锁,则不互斥
        Foo foo =new Foo();
        Thread t1 =new Thread(){
            @Override
            public void run() {
                foo.methodA();
            }
        };
        Thread t2 =new Thread(){
            @Override
            public void run() {
                foo.mothodB();
            }
        };
        t1.start();
        t2.start();

    }
}

class Foo {
    public synchronized void methodA() {
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName() + "正在执行A方法");
            Thread.sleep(5000);
            System.out.println("A方法执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void mothodB() {
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName() + "正在执行B方法");
            Thread.sleep(5000);
            System.out.println("B方法执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}